// https://www.lintcode.com/problem/binary-tree-level-order-traversal-ii/description

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A tree
     * @return: buttom-up level order a list of lists of integer
     */
    vector<vector<int>> levelOrderBottom(TreeNode * root) {
        vector<vector<int>> result;
        if (!root) return result; //重要
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty())
        {
            int len = q.size();
            vector<int> tmp_vec;
            for (int i = 0; i < len; ++i)
            {
                TreeNode * tmp = q.front();
                tmp_vec.push_back(tmp->val);
                q.pop();
                if (tmp->left) q.push(tmp->left);
                if (tmp->right) q.push(tmp->right);
            }
            result.push_back(tmp_vec);
        }
        reverse(result.begin(), result.end());
        return result;
    }
};